<template>
  <div class="containers">
    <div class="container">
      <div class="handle-box">
        <el-button type="primary" icon="el-icon-plus" class="handle-add mr10" @click="addregion"
                   size="mini">添加
        </el-button>
      </div>

      <el-table :data="tableData" class="table" ref="multipleTable" header-cell-class-name="table-header" border
                size="mini" :height="$tableHight"
                @selection-change="handleSelectionChange" v-loading="loading">
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="name" label="标题栏目"></el-table-column>

        <el-table-column label="展示图片" align="center">
          <template slot-scope="scope">
            <el-image class="table-td-thumb" :src="scope.row.img"
                      :preview-src-list="[scope.row.img]"></el-image>
          </template>
        </el-table-column>

        <el-table-column prop="is_shop" label="是否商家可用">
          <template slot-scope="scope">
            {{ scope.row.is_shop == 1 ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="is_display" label="是否展示">
          <template slot-scope="scope">
            {{ scope.row.is_display == 1 ? '是' : '否' }}
          </template>
        </el-table-column>

        <el-table-column prop="sort" label="排序" width="120">
          <template slot-scope="scope">
            <el-input size="mini" v-model="scope.row.sort" @blur="operations(scope.row, 1)"
                      style="text-align: center"></el-input>
          </template>
        </el-table-column>

        <el-table-column prop="CreatedAt" label="创建时间">

          <template slot-scope="scope">
            {{ $clearTimer(scope.row.CreatedAt) }}
          </template>
        </el-table-column>


        <el-table-column label="操作" width="220" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" icon="el-icon-delete" class="red"
                       @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
            <el-button type="text" size="mini"
                       @click="copy('/pages/commodity/list?id=' + scope.row.ID)">复制链接
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
                       :page-size="query.pageSize" :total="pageTotal"
                       @current-change="handlePageChange"></el-pagination>
      </div>
    </div>

    <!-- 编辑/添加弹出框 -->
    <el-dialog :title="type ? '编辑' : '添加'" :visible.sync="editVisible" width="30%">
      <el-form ref="form" :model="form" label-width="70px">
        <el-form-item label="标题栏目">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="form.sort" type="Number"></el-input>
        </el-form-item>
        <el-form-item label="是否商家可用">
          <el-switch :active-value="1" :inactive-value="0" v-model="form.is_shop"></el-switch>
        </el-form-item>
        <el-form-item label="是否展示">
          <el-switch :active-value="1" :inactive-value="0" v-model="form.is_display"></el-switch>
        </el-form-item>
        <el-form-item label="分区类型">
          <!-- <el-input v-model="form.is_single" type="Number"></el-input> -->

          <el-select v-model="form.is_single" placeholder="请选择分区类型" size="small" class="mr10">
            <el-option v-for="(item) in singles" :key="item.ID" :label="item.name"
                       :value="item.ID"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="展示图片">
          <div style="color:red;">比例:100/100</div>
          <el-upload class="avatar-uploader" :action="upload + '/'" :show-file-list="false" :data="upimg"
                     :on-success="handleAvatarSuccess" :before-upload="beforeupload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
				<el-button @click="cancel">取 消</el-button>
				<el-button type="primary" @click="saveEdit">确 定</el-button>
			</span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'basetable',
  data() {
    return {
      options: [{ name: '普通', ID: 0 }, { name: '百元区', ID: 1 }, { name: '千元区', ID: 2 }, {
        name: '万元区',
        ID: 3
      }], //分区类型 下拉选项
      form: {
        name: '',
        img: '',
        sort: 0,
        is_single: 0,
        is_shop: 0,
        is_display: 0
      },
      query: {
        pageIndex: 1,
        pageSize: 20
      },
      upimg: {
        token: '',
        key: new Date().valueOf()
      },
      code: 0,
      upload: '',
      tableData: [],
      multipleSelection: [],
      editVisible: false,
      pageTotal: 0,
      imageUrl: '',
      type: 0,
      loading: false,
      singles: [
        {
          ID: 0,
          name: '普通区'
        },
        {
          ID: 1,
          name: '报单区'
        },
       ]
    }
  },
  created() {
    this.getToken().then(res => {
        this.upimg.token = res.data.token
        this.url = res.data.url
        this.upload = res.data.upload
        console.log(res)
      },
      function() {
        console.log('请求失败处理')
      }
    )
    this.getData()
  },
  methods: {

    copy(row) {
      // 创建一个input框
      const input = document.createElement('input')
      // 将指定的DOM节点添加到body的末尾
      document.body.appendChild(input)
      // 设置input框的value值为复制的值
      const address = row
      input.setAttribute('value', address)
      // 选取文本域中的内容
      input.select()
      // copy的意思是拷贝当前选中内容到剪贴板
      // document.execCommand（）方法操纵可编辑内容区域的元素
      // 返回值为一个Boolean，如果是 false 则表示操作不被支持或未被启用
      if (document.execCommand('copy')) {
        document.execCommand('copy')
      }
      // 删除这个节点
      document.body.removeChild(input)
      // 弹窗：复制成功
      this.$message.success('复制成功')
      //
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.form.img = this.url + res.key
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeupload(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('上传头像图片只能是 JPG、PNG 格式!')
        return false
      }
      if (file.size / 1024 / 1024 > 1) {
        this.$message.error('上传图标大小不能超过 1M!')
        return false
      }
      let types = file.name.split('.')//获取图片格式
      this.upimg.key = this.$template + '/home/' + new Date().valueOf() + '.' + types[types.length - 1]
      console.log(this.upimg.key)
    },
    //获取数据
    getData() {
      this.loading = true
      this.request('admin/partition/', 'get', { page: this.query.pageIndex, size: this.query.pageSize }).then(res => {
        console.log(res)
        this.tableData = res.data.data
        this.pageTotal = res.data.total
      })
      this.loading = false
    },
    // 编辑
    handleEdit(e) {
      this.editVisible = true
      this.form = e
      this.imageUrl = e.img
      this.type = 1
    },
    cancel() {
      this.editVisible = false
      this.form = {
        name: '',
        img: '',
        sort: 0,
        is_single: 0,
        is_shop: 0,
        is_display: 0
      }
      this.getData()
    },
    // 修改排序
    operations(e, code) {
      e.sort = Number(e.sort)
      e.is_single = Number(e.is_single)
      e.is_shop = Number(e.is_shop)
      e.is_display = Number(e.is_display)
      this.request('admin/partition/', 'put', e).then(res => {
        if (res.errno == 0) {
          this.$message.success(res.errmsg)
          this.getData()
        } else {
          this.$message.error(res.errmsg)
        }
      })
      this.editVisible = false

    },
    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.request('admin/partition/', 'delete', { ID: row.ID }).then(res => {
            if (res.errno == 0) {
              this.$message.success(res.errmsg)
              this.tableData.splice(index, 1)
              this.getData()
            } else {
              this.$message.error(res.errmsg)
            }
          })
        })
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 添加
    addregion() {
      this.form = {
        name: '',
        img: '',
        sort: 0,
        is_single: 0,
        is_shop: 0,
        is_display: 0
      }
      this.type = 0
      this.imageUrl = ''
      this.editVisible = true
    },

    // 添加/修改
    saveEdit() {
      console.log(this.form)
      if (!this.form.name) return this.$message.error('请输入分区')
      if (!this.form.img) return this.$message.error('请上传图片')

      this.form.is_single = Number(this.form.is_single)
      this.form.sort = Number(this.form.sort)
      this.request('admin/partition/', this.type ? 'put' : 'post', this.form).then(res => {
        if (res.errno == 0) {
          this.$message.success(res.errmsg)
          this.form = {
            name: '',
            img: '',
            sort: 0,
            is_single: 0,
            is_shop: 0,
            is_display: 0
          }
        } else {
          this.$message.error(res.errmsg)
        }
        this.getData()
      })
      this.editVisible = false
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, 'pageIndex', val)
      this.getData()
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.el-upload--text {
  width: 200px !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  /* width: 100px; */
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 178px;
  display: block;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 30px;
  height: 30px;
  border-radius: 2px;

  .el-image img {
    object-fit: cover;
  }
}

/* 设置分页按钮样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 使用 /deep/ 或 >>> 来穿透 scoped 样式 */
::v-deep .el-table th.el-table__cell {
  background-color: #f2f2f2;
  /* 设置表头颜色 */
  color: #333;
  /* 设置表头文字颜色 */
}
</style>
